<template>
  <div class="el-select itemCategory-treeselect">
    <treeselect
      v-bind="$attrs"
      :value="treeValue"
      :options="itemCategorys"
      :normalizer="itemNormalizer"
      searchable
      clearable
      show-count
      is-default-expanded
      placeholder="选择物料类别"
      @select="itemCategorySelect"
      v-on="$listeners"
    />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getItemCategoryTreeByCpyCode } from '@/api/base/itemCategory'

export default {
  components: { Treeselect },
  model: {
    prop: 'value' // , // 自定义prop属性
    // event: 'handSelect' // 自定义它的触发方法名
  },
  props: {
    value: {
      type: String,
      default: null,
      required: false
    },
    valueField: {
      type: String,
      default: 'id',
      required: false
    },
    curItemId: {
      type: String,
      default: null,
      required: false
    }
  },
  data() {
    return {
      itemCategorys: []
    }
  },
  computed: {
    treeValue: {
      get() {
        if (this.value === '') {
          return null
        }
        return this.value
      },
      set(val) {
        this.value = val
      }
    }
  },
  watch: {
    curItemId() {
      getItemCategoryTreeByCpyCode(this.curItemId).then(res => {
        this.itemCategorys = res.data
      })
    }
  },
  created() {
  },
  mounted() {
    if (!this.curItemId) {
      getItemCategoryTreeByCpyCode(this.curItemId).then(res => {
        this.itemCategorys = res.data
      })
    }
  },
  methods: {
    itemNormalizer(node) {
      return {
        id: node[this.valueField],
        label: node.catName
      }
    },
    itemCategorySelect(node, instanceId) {
      this.$emit('ItemCategoryClick', node, instanceId)
    }
  }
}
</script>
<style scoped>
.itemCategory-treeselect{
  padding-left: 3px;
  height:28px;
}
</style>
